<!-- 项目附件电子签章选择页面 -->
<template>
  <el-container class="electronicSignature">
    <el-main class="mainDetails">
      <div>
        <SearchPanel title="查询条件" show-fold @setHeight="setHeight">
          <div ref="queryFormBox" class="search-flex-box">
            <MyForm
              ref="formRef"
              v-model="queryParams"
              :form-option="formOption"
              :select-list="dicLists"
              @handleEvent="handleEvent"
            >
              <template #orgIds>
                <div @click="activeUnit">
                  <el-input v-model="customCheck" class="construct" :readonly="true" placeholder="请选择">
                    <i slot="suffix" class="el-icon-more" />
                  </el-input>
                </div>
              </template>
            </MyForm>
            <div class="searchBtn">
              <el-button type="primary" class="pms-button-primary" @click="doSearch">查询</el-button>
              <el-button class="pms-button-primary" size="small" @click="dialogCheckbox = true">
                自定义列
              </el-button>
            </div>
          </div>
        </SearchPanel>
        <SearchList title="查询结果" style="margin-top: 16px">
          <template #header-btn>
            <BtnConfig ref="btnConfigRef" :btn-configs="btnOption" @propClick="btnClick" />
          </template>
          <template #body>
            <MyTable
              id="id"
              ref="myTableRef"
              :table-data="tableData"
              :columns="colOption"
              :col-option-enum="dicLists"
              :isShowCheckbox="true"
            >
              <template #docName="{ scope }">
                <el-button type="text" @click="goPage(scope)">{{ scope.docName }}</el-button>
              </template>
              <template #state="{ scope }">
                <el-button type="text" @click="goState(scope)">
                  {{ signStateVal(scope.state) }}
                </el-button>
              </template>
            </MyTable>
            <pagination
              v-if="pageParam.total > 10"
              :total="pageParam.total"
              :page.sync="pageParam.pageNum"
              :limit.sync="pageParam.pageSize"
              @pagination="doSearch"
            />
          </template>
        </SearchList>
        <!-- 选择建设单位 -->
        <el-dialog
          v-dialogDrag
          title="选择建设单位"
          width="30%"
          :append-to-body="true"
          :modal-append-to-body="true"
          :modal="true"
          :close-on-click-modal="false"
          :lock-scroll="true"
          class="pms-dialog"
          :visible.sync="dialogUnit"
        >
          <div class="dialogForm">
            <ChooseUnit ref="chooseUnitRef" v-model="queryParams.orgIds" />
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" class="pms-button-primary" size="small" @click="verifyUnit">确 定</el-button>
            <el-button type="primary" class="pms-button-primary" @click="dialogUnit = false">取 消</el-button>
          </div>
        </el-dialog>
        <!-- 打开签署状态弹框列表-审批流程 -->
        <el-dialog
          v-if="dialogState"
          v-dialogDrag
          title="审批流程"
          width="50%"
          :append-to-body="true"
          :modal-append-to-body="true"
          :modal="true"
          :close-on-click-modal="false"
          :lock-scroll="true"
          class="pms-dialog"
          :visible.sync="dialogState"
        >
          <div class="dialogForm">
            <SignStatusList ref="signStatusRef" :sign-status-id="signStatusId" />
          </div>
        </el-dialog>
        <el-dialog
          v-dialogDrag
          title="列表字段配置"
          width="50%"
          :append-to-body="true"
          :modal-append-to-body="true"
          :modal="true"
          :close-on-click-modal="false"
          :lock-scroll="true"
          class="pms-dialog"
          :visible.sync="dialogCheckbox"
        >
          <div class="dialogCheckbox">
            <SetDynamics
              ref="customRef"
              :fixed-check-option="fixedCheckOption"
              :custom-check-option="customCheckOption"
            />
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button class="pms-button-primary" size="small" @click="activeCustomCheck">确 定</el-button>
            <el-button class="pms-button-primary" size="small" @click="dialogCheckbox = false">取 消</el-button>
          </div>
        </el-dialog>
      </div>
    </el-main>
  </el-container>
</template>

<script>
// import HeaderTitle from '@/components/basic/HeaderTitle'
import axios from 'axios'
import SearchPanel from '@/components/basic/SearchPanel'
import MyForm from '@/components/basic/myForm'
import SearchList from '@/components/basic/SearchList'
import MyTable from '@/components/basic/myTable'
import SysConst from '@/common/const'
import SetDynamics from '@/components/basic/setDynamics.vue'
import BtnConfig from '@/components/basic/btnConfig.vue'
import ChooseUnit from '../eleSignVerConfig/chooseUnit.vue'
import SignStatusList from '@/components/eleSignature/signStatusList.vue'
import { getDropdownData } from '@/api/common' // 字典接口
import { formOption, colOption, btnOption, customCheckOption } from '.'
import { queryOrgApi } from '@/api/attachManagement/electronicSign/eleSignVerConfig'
import {
  queryCompleteProject, addCompleteProject, checkPersonApi, getSignFlowDocUrlsApi } from '@/api/attachManagement/electronicSign/electronicSignature'
import { getPrjStageApi, getPrjNodeNameApi } from '@/api/attachmentInfo'

export default {
    name: 'ElectronicSignature',
    components: {
        // HeaderTitle,
        SearchPanel,
        SearchList,
        MyTable,
        MyForm,
        SetDynamics,
        BtnConfig,
        ChooseUnit,
        SignStatusList
    },
    inject: ['workDetail'],
    data() {
        return {
            queryParams: {
                prjYear: new Date().getFullYear().toString()
            }, // 查询数据
            formOption, // 查询条件配置项
            customCheck: '', // 查询条件建设单位选择后显示
            dialogUnit: false, // 建设单位弹框
            tableData: [], // 列表数据
            colOption, // 列表表头
            btnOption, // 列表按钮
            fixedCheckOption: colOption, // 固定字段
            customCheckOption, // 自定义字段
            dialogCheckbox: false, // 自定义列表弹框
            dicLists: {}, // 下拉框字典选项集合
            dialogState: false, // 审批流程列表弹框
            signStatusId: '', // 审批流程Id
            // 分页信息
            pageParam: {
                pageSize: SysConst.PAGESIZE, // 每页显示val条
                pageNum: SysConst.CURRENT_PAGE, // 当前页
                total: SysConst.TOTAL // 总数
            },
            currentNode: '' // 当前节点
        }
    },
    computed: {
        // 工作项信息
        newWorkDetail() {
            return this.workDetail()
        },
        // workItemId
      queryWorkInfo() {
           return this.$route.query
      }
    },
    created() {
        this.$nextTick(() => {
            this.setHeight(false)
        })
        this.currentNode = this.newWorkDetail?.bizObject.nodeCode
        this.getDictData()
        this.getPrjStage()
        this.getPrjNodeName([])
        this.queryOrg()
        this.doSearch()
    },
    methods: {
        // 查看数据
        doSearch(item) {
            const params = {
                pageNum: item?.page || SysConst.CURRENT_PAGE,
                pageSize: item?.limit || SysConst.PAGESIZE,
                ...this.queryParams
            }
            console.log(params, 'search');
            queryCompleteProject(params).then(res => {
              if (+res.code !== 200) {
                  return Promise.reject(res)
                }
                this.tableData = res.data?.records
                this.pageParam.total = res.data?.total || 0
                this.pageParam.pageSize = item?.limit || SysConst.PAGESIZE
                this.pageParam.pageNum = item?.page || SysConst.CURRENT_PAGE
            })
        },
        // 枚举签署状态
        signStateVal(state) {
            // 显示检验
            if (!state && state !== 0) return ''
            if (state === '-') return state
            let propName = '' // 定义返回字段
            const propObj = this.dicLists['SIGN_STATE2']?.find(sign => sign.dictId === state) || {}
            propName = JSON.stringify(propObj) !== '{}' ? propObj.dictName : ''
            return propName
        },
        // 查询条件事件
        handleEvent(prop, val) {
            console.log(prop, val, 'hjhjbj')
            if (prop === 'prjStatusNewList') {
                this.getPrjNodeName(val)
                this.queryParams.nodeNameList = []
            }
        },
        // 列表按钮点击事件
        btnClick(fun, row) {
            this[fun](row)
        },
        // 重置
        // resetSearch() {
        //     this.$refs.formRef.reset()
        //     this.doSearch()
        // },
        // 选择建设单位
        activeUnit() {
            this.dialogUnit = true
        },
        // 确定单位
        verifyUnit() {
            const { checkedKeys, checkedNodes } = this.$refs.chooseUnitRef
            this.$set(this.queryParams, 'orgIds', checkedKeys)
            const list = checkedNodes.map((item) => item.orgName)
            this.customCheck = list.join().replaceAll(',', '、')
            this.dialogUnit = false
        },
        // 自定义列字段弹框-点击确认
        activeCustomCheck() {
            const list = this.$refs.customRef.checkboxValue
            this.colOption = [...colOption, ...list]
            this.dialogCheckbox = false
        },
        // 点击去往E签宝
        goPage(row) {
            getSignFlowDocUrlsApi({ id: row.id }).then(res => {
              if (+res.code !== 200) {
                  return Promise.reject(res)
                }
                if (res.data) {
                    axios.get(res.data, {
                        responseType: 'blob',
                        cache: true,
                        headers: {
                            'Content-Disposition': 'inline'
                        }
                    }).then(r => {
                            const blob = new Blob([r.data], { type: 'application/pdf;charset-UTF-8' })
                            // const blob = new Blob([r.data], { type: r.headers['content-type'] })
                            const url = window.URL.createObjectURL(blob)
                            window.open(url, '_blank')
                            URL.revokeObjectURL(url) // 释放内存
                    })
                }
            })
        },
        // 点击签署状态
        goState(row) {
            console.log(row, '点击签署状态')
            this.dialogState = true
            this.signStatusId = row.id.toString()
        },
        // 校验是否本人数据/是否内部人员接口
        async checkPerson(params) {
            const res = await checkPersonApi(params)
            if (res.success) {
                return res.data
            }
        },
        // 获取下拉框数据
        async getDictData() {
            const arr = ['IS_NEWBUSINESS', 'PROJ_TYPE', 'SIGN_STATE2', 'BUILD_MODES','FILE_STATE']
            const promises = arr.map(item => getDropdownData(item))
            const results = await Promise.all(promises)
            arr.forEach((item, i) => {
                this.$set(this.dicLists, item, results[i].data ?? [])
            })
            this.$set(this.dicLists, 'FILE_UPLOAD_MODES', SysConst.UPLOAD_MODES)
        },
        // 查询建设单位
        async queryOrg() {
            const res = await queryOrgApi()
            this.$set(this.dicLists, 'BUILD_UNIT', res.data)
        },
        // 获取项目阶段字典
        async getPrjStage() {
            const res = await getPrjStageApi()
            this.$set(this.dicLists, 'PRO_STAGE', res.data)
        },
        // 获取项目节点字典
        async getPrjNodeName(val) {
            const res = await getPrjNodeNameApi({ stageList: val.join() ?? '' })
            this.$set(this.dicLists, 'PRO_NODE', res.data)
        },
        // 设置高度
        setHeight(isFold) {
            const child = this.$refs.formRef.$refs
            const height = (formOption.itemData.length / 3).toFixed() - 0
            // const height = (child.queryFormRef.$children.length / 3).toFixed() - 0
            this.$refs.queryFormBox.style.height = isFold ? `${height * 24}px` : '54px'
            child.myFormRef.style.height = isFold ? `${height * 24}px` : '54px'
        },
        // 项目选择
        async prjAttachSelect(row) {
            if (row?.length < 1) {
              return this.$message.info('请至少选择一条数据')
            }
            const idList = []
            row.map(item => {
              idList.push(item.docId)
            })
            const taskId = this.newWorkDetail?.bizObject?.bizSeq
            console.log(idList, taskId)
            await addCompleteProject({ idList, taskId }).then(res => {
              if (+res.code === 200) {
                this.$emit('closeSelectWin')
                return this.$message.success('选择项目成功')
              }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.search-flex-box {
    // display: flex;
    // justify-content: space-between;
    height: auto;
}
.searchBtn {
    width: 100px;
    margin-left: auto;
    display: flex;
    margin-top: 4px;
    flex-direction: column;
    .el-button + .el-button {
        margin-left: 0;
        margin-top: 8px;
    }
}

.electronicSignature {
    width: 100%;
    .mainDetails {
        padding: 0 25px;
    }
    .topRemark {
        // background-color: #fdf5e6;
        background-color: #ffefd5;
        width: 100%;
        height: 40px;
        line-height: 40px;
        padding-left: 10px;
        font-size: 14px;

        .asterisk {
            color: #f00;
            margin-right: 2px;
            font-size: 18px;
        }
    }

    .customBtn {
        height: 20px;
        line-height: 20px;
        font-size: 14px;
        margin: 10px 20px 10px 90%;
        cursor: pointer;

        .el-icon-s-tools {
            font-size: 20px;
            color: #999;
            margin-right: 6px;
        }
    }
}

.el-button--text {
    color: #02A7F0;
}

.el-button--primary {
    color: #fff;
}
.dialog-footer {
    display: flex;
    justify-content: center;
}
::v-deep .el-button + .el-button {
    color: #fff;
}
// 弹框样式
::v-deep .el-dialog__body {
    overflow-y: auto;
}
// 滚动条样式
::v-deep .el-dialog__body::-webkit-scrollbar {
  // 滚动条整体样式
  width: 6px; //高宽分别对应横竖滚动条的尺寸
  height: 10px;
}
::v-deep .el-dialog__body::-webkit-scrollbar-thumb {
  // 滚动条里面小方块
  border-radius: 10px;
  // -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: #f2f3f5;
}
</style>
./attachSignInfoSelect
